package com.szholly.plug.activity.interceptor.defulat;

import java.util.Date;

import org.springframework.stereotype.Component;

import com.szholly.plug.activity.core.BpmException;
import com.szholly.plug.activity.interceptor.BpmHandleOptionBase;
import com.szholly.plug.activity.interceptor.BpmInterceptorRegister;
import com.szholly.plug.activity.interceptor.OptionInfo;
import com.szholly.plug.activity.model.BpmConfigCache;
import com.szholly.plug.activity.model.BpmConfigRow;
import com.szholly.plug.activity.model.BpmTaskConfigRow;
import com.szholly.plug.activity.model.BpmWorklistRow;
import com.szholly.plug.activity.model.BpmWorklistTable;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.general.GlobalDataType;
import com.szholly.data.general.IQueryMap;
import com.szholly.data.general.QueryMap;
import com.szholly.data.general.RowBase;

/**
 * 记录流程待办
 */
@Component
public class WorkListBpmOption extends BpmHandleOptionBase {

	/**
	 * 注册拦截接口
	 */
	static {
		WorkListBpmOption interceptor = new WorkListBpmOption();
		BpmInterceptorRegister.RegDbInterceptor(interceptor);
	}

	/**
	 * 流程任务操作
	 * 
	 * @param optionInfo
	 */
	@Override
	public void taskOption(OptionInfo optionInfo) {
		String pTaskId = optionInfo.TaskPId;
		if (!StringUtils.IsNullOrSpace(pTaskId)) {
			String[] ids = pTaskId.split(",");
			for (String id : ids) {
				BpmWorklistTable.getSingleRef().delWorkList(id);
			}
		}

		String taskId = optionInfo.TaskId;
		String taskDefinitionKey = optionInfo.TaskDefinitionKey;
		String taskName = optionInfo.TaskState;
		String taskAssignees = optionInfo.TaskAssignees;

		if (!StringUtils.IsNullOrSpace(taskId)) {
			String[] ids = taskId.split(",");
			String[] definitionKeys = taskDefinitionKey.split(",");
			String[] names = taskName.replace("会签(", "").replace(")", "")
					.split(",");

			for (int i = 0; i < ids.length; i++) {
				String id = ids[i];
				String task = definitionKeys[i];
				String name = names[i];
				String user = getTaskAssignees(taskAssignees, task);

				saveWork(optionInfo.BpmId, id, task, name, user,
						optionInfo.BusinessRow, optionInfo);
			}
		}
	}

	/**
	 * 保存待办事项
	 * 
	 * @param pDefId
	 *            流程定义ID
	 * @param taskId
	 *            当前任务ID
	 * @param taskName
	 *            当前任务名称
	 * @param users
	 *            当前节点的审批人列表
	 * @param row
	 *            当前数据行
	 */
	private void saveWork(String pDefId, String taskId, String taskDefinId,
			String taskName, String users, RowBase row, OptionInfo optionInfo) {
		BpmWorklistRow work = null;
		IQueryMap queryMap = new QueryMap();
		queryMap.getWhereMap().put(BpmWorklistRow.FIELD_ITaskid, taskId);
		work = BpmWorklistTable.getSingleRef().getEntity(BpmWorklistRow.class,
				queryMap);
		if (work == null) {
			work = new BpmWorklistRow();
		} else {
			return;
		}
		work.setDBegintime(new Date());
		work.setITaskid(taskId);
		work.setTaskDefinid(taskDefinId);
		work.setSDefinid(pDefId);
		work.setSTaskname(taskName);
		work.setSAssingusers(users);
		
		String key = (String) row.getValue(GlobalDataType.String,
				optionInfo.pTable.getGUIDFieldName());
		if(StringUtils.IsNullOrSpace(key)){
			throw new BpmException("不能获取业务数据主键值，流程待办保存失败！");
		}
		work.setKey(key);

		BpmConfigRow configRow = BpmConfigCache.getConfig(pDefId);
		if (configRow != null) {
			work.setSDefinname(configRow.getSDefitionName());
			work.setSFormurl(configRow.getSFormurl());
			work.setFormName(configRow.getFormName());
			work.setFormPopId(configRow.getFormPopId());
			work.setTableName(configRow.getTableName());
			work.setSGroup(configRow.getSGroup());
			String businessFields = configRow.getBusiness();
			if (!StringUtils.IsNullOrSpace(businessFields)) {
				String[] fields = businessFields.split(",");
				String business = "";
				for (String field : fields) {
					String value = (String) row.getValue(GlobalDataType.String,
							field);
					if (StringUtils.IsNullOrSpace(value)) {
						business += ",";
					} else {
						business += value + ",";
					}
				}
				business = business.substring(0, business.length() - 1);
				work.setBusiness(business);
			}

			BpmTaskConfigRow configTaskRow = BpmConfigCache.getTaskConfig(
					pDefId, taskDefinId);
			if (configTaskRow != null) {
				// 超时时间
				String sx = configTaskRow.getRemindersQx();
				// 创建时间
				String cjsj = configTaskRow.getRemindersCj();
				// 到期时间
				String wcqx = configTaskRow.getRemindersWc();
				// 通知模板
				String body = configTaskRow.getRemindersMb();
				work.setRemindersQx(sx);
				if (StringUtils.IsNullOrSpace(configTaskRow.getRemindersQy())
						|| !configTaskRow.getRemindersQy().equals("1")
						|| StringUtils.IsNullOrSpace(body)
						|| StringUtils.IsNullOrSpace(sx)
						|| (StringUtils.IsNullOrSpace(cjsj) && StringUtils
								.IsNullOrSpace(wcqx))) {
					work.setHasCJReminders("");
					work.setHasWCReminders("");
				} else {
					if (StringUtils.IsNullOrSpace(cjsj)) {
						work.setHasCJReminders("");
					} else {
						work.setHasCJReminders("1");
					}
					if (StringUtils.IsNullOrSpace(wcqx)) {
						work.setHasWCReminders("");
					} else {
						work.setHasWCReminders("1");
					}
				}
			} else {
				work.setHasCJReminders("");
				work.setHasWCReminders("");
			}
		} else {
			work.setSDefinname("");
			work.setSFormurl("");
			work.setSGroup("");
			work.setBusiness("");
			work.setHasCJReminders("");
			work.setHasWCReminders("");
		}
		BpmWorklistTable.getSingleRef().save(work);
	}

	/**
	 * 获取当前任务的审批人
	 * 
	 * @param taskKey
	 * @return
	 */
	private String getTaskAssignees(String assignees, String taskKey) {
		String[] taskUserList = assignees.split(":");
		// 找到当前的任务审批人
		String taskitem = "";
		for (String item : taskUserList) {
			if (item.contains(taskKey)) {
				taskitem = item;
				break;
			}
		}
		String[] users = taskitem.split(",");
		String workUsers = "";
		for (int i = 2; i < users.length; i += 2) {
			workUsers += users[i] + "," + users[i + 1] + ",";
		}
		if (workUsers != "") {
			workUsers = workUsers.substring(0, workUsers.length() - 1);
		}
		return workUsers;
	}
}
